package com.atguigu.dga.ds.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.ds.bean.TDsTaskDefinition;
import com.atguigu.dga.ds.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.ds.service.TDsTaskDefinitionService;
import com.atguigu.dga.meta.constant.CodeConst;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangchen
 * @since 2023-11-22
 */
@Service
@DS("ds")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {


    //  把当天运行最后一次实例对应的任务定义取出来  map<表名,任务定义>
    // select * from t_ds_task_definition
    //          where code in (select task_code  ##取该任务的任务定义的code
    //                         from t_ds_task_instance ti1
    //                         where id = (select max(id)   #当天某个同样任务名称的任务中 成功的 id最大
    //                                     from t_ds_task_instance ti2
    //                                     where ti1.name = ti2.name
    //                                       and date_format(submit_time, '%Y-%m-%d') = '2023-05-02')
    //                                      and  state=7
    //                          )
    @Override
    public Map<String, TDsTaskDefinition> getTaskDefinitionMap(String assessDate) {
        //    select * from t_ds_task_definition  where code in ( select task_code  from  t_ds_task_instance ti1 where  id = (select  from  t_ds_task_instance ti2  where  ti1.name =ti2.name and date_format(   )
        QueryWrapper<TDsTaskDefinition> queryWrapper = new QueryWrapper<TDsTaskDefinition>().inSql("code", "select task_code  " +
                "                         from t_ds_task_instance ti1\n" +
                "                         where id = (select max(id)    " +
                "                                     from t_ds_task_instance ti2\n" +
                "                                     where ti1.name = ti2.name\n" +
                "                                       and date_format(submit_time, '%Y-%m-%d') = '" + assessDate + "')\n" +
                "                                      and  state=" + CodeConst.TASK_STATE_SUCCESS);
        List<TDsTaskDefinition> tDsTaskDefinitionList = list(queryWrapper);

        for (TDsTaskDefinition tDsTaskDefinition : tDsTaskDefinitionList) {
            String taskParams = tDsTaskDefinition.getTaskParams();
            String sql=   getSQLfromParam(taskParams);
            tDsTaskDefinition.setSql(sql);
        }



        //list转map
        Map<String, TDsTaskDefinition> taskDefinitionMap =
                tDsTaskDefinitionList.stream()
                        .collect(Collectors.toMap(tDsTaskDefinition -> tDsTaskDefinition.getName(), tDsTaskDefinition -> tDsTaskDefinition));

        return taskDefinitionMap;
    }

    private String getSQLfromParam(String taskParams) {

        //把taskParams转jsonObj
        JSONObject taskParamJsonObj = JSON.parseObject(taskParams);
        String rawScript = taskParamJsonObj.getString("rawScript");

        //从shell中切割出sql
        //删除换行
        rawScript = rawScript.replace("\n", " ");
        //起始点
        int startIdx = rawScript.indexOf("with");
        if(startIdx==-1){
            startIdx=rawScript.indexOf("insert");
        }
        if(startIdx==-1){
            return  null;
        }
        //结束点
        int endIdx = rawScript.indexOf(";", startIdx);
        if(endIdx==-1){
            rawScript.indexOf("\"",startIdx );
        }
        if(endIdx==-1){
            return  null;
        }

        String sql = rawScript.substring(startIdx, endIdx);
        return sql;

    }
}
